
package com.scalar.chiptrack.operations.proformainvoice.actions;

import java.util.HashMap;
import java.util.ArrayList;
import java.util.StringTokenizer;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.mail.internet.InternetAddress;

import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionForm;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.operations.proformainvoice.forms.SendProFormaMailForm;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.dao.UserDAO;
import com.scalar.chiptrack.utils.Mailer;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.operations.proformainvoice.actions.ProFormaAction;
import com.scalar.chiptrack.sales.dao.SalesOrderDAO;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.sales.SalesOrder;
import com.scalar.chiptrack.sales.ContactPerson;


public class SendProFormaMailAction extends ChipTrackAction
{

    public SendProFormaMailAction ()
    {

    }

    public ActionForward execute ( ActionMapping mapping,
                                   ActionForm form,
                                   HttpServletRequest request,
                                   HttpServletResponse response )
    {

        HashMap info = new HashMap ();
        request.setAttribute ( SessionKeys.INFO_MESSAGES, info );
        HashMap errors = new HashMap ();
        request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
        SendProFormaMailForm sendProFormaMailForm = ( SendProFormaMailForm ) form;
        String salesOrderId = request.getParameter ( "salesOrderId" );
        SalesOrder salesOrder = null;
        boolean success = false;
        String action = request.getParameter ( "action" );
        request.setAttribute ( "salesOrderId", salesOrderId );

        String salesNo1 = null;
        String email = null;
        String customerPO = null;
        String customerName = null;
        ArrayList contactPersons = null;
        String emails = null;
        String subject = null;
        String[] toUsers = null;
        String types[] = null;
        HttpSession session = request.getSession ();
        User user = ( User ) session.getAttribute ( SessionKeys.USER_KEY );

        try
        {
            if ( salesOrderId != null )
            {
                salesOrder = SalesOrderDAO.loadSalesOrder ( salesOrderId );
                salesNo1 = salesOrder.getSalesOrderNo ();
                email = salesOrder.getEmail ();
                customerPO = salesOrder.getCustomerPO ();
                customerName = salesOrder.getCustomerName ();
            }
        }
        catch ( ScalarException se )
        {
            System.out.println ( "Exception while loading sales order No..... " );
            se.getRootCause ().printStackTrace ();
        }


        String mimeType = sendProFormaMailForm.getAttachMIMEType ();
        if ( ( mimeType == null ) || ( mimeType.trim ().length () == 0 ) )
        {
            mimeType = "PDF";
            sendProFormaMailForm.setAttachMIMEType ( "PDF" );
        }

        if ( user == null )
        {
            session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, "/sendProFormaMail.do?" + request.getQueryString () );
            return ( mapping.findForward ( "login" ) );
        }
        String from = user.getEmail ();

        if ( ( action != null ) && ( action.equalsIgnoreCase ( "save" ) ) )
        {
            try
            {
                String to = StringUtils.concatStrings ( sendProFormaMailForm.getToUsers (), Mailer.EMAIL_SEPARATOR );
                String cc = StringUtils.concatStrings ( sendProFormaMailForm.getCcUsers (), Mailer.EMAIL_SEPARATOR );
                String bcc = StringUtils.concatStrings ( sendProFormaMailForm.getBccUsers (), Mailer.EMAIL_SEPARATOR );

                to = Mailer.getNotifiableEmails ( to, false );
                cc = Mailer.getNotifiableEmails ( cc, false );
                bcc = Mailer.getNotifiableEmails ( bcc, false );
                if ( cc == null )
                {
                    sendProFormaMailForm.setCcUsers ( null );
                }
                if ( bcc == null )
                {
                    sendProFormaMailForm.setBccUsers ( null );
                }
                subject = sendProFormaMailForm.getSubject ();

                if ( subject == null )
                {
                    subject = " Pro Forma Invoice for : " + customerPO;

                }
                sendProFormaMailForm.setSubject ( subject );
                String message = sendProFormaMailForm.getMessage ();
                String host = request.getHeader ( "HOST" );

                String proFormaFile = null;
                if ( "PDF".equalsIgnoreCase ( mimeType ) )
                    proFormaFile = ProFormaAction.getProFormaPDFFile ( host, salesOrderId );
                else
                    proFormaFile = ProFormaAction.getProFormaHtmlFile ( host, salesOrderId );

                String[] mailAttachments = null;

                String isConfirm = ( String ) session.getAttribute ( "isConfirm" );
                String sysAdminEmail = ConfigManager.getSysAdminEmail ();
                String companyEmailId = sysAdminEmail.substring ( sysAdminEmail.indexOf ( "@" ) + 1, sysAdminEmail.length () );
                if ( isConfirm == null )
                {
                    to = Mailer.getNotifiableEmails ( to, false );
                    cc = Mailer.getNotifiableEmails ( cc, false );
                    bcc = Mailer.getNotifiableEmails ( bcc, false );
                    InternetAddress[] toAddress = null;
                    InternetAddress[] ccAddress = null;
                    InternetAddress[] bccAddress = null;

                    String emailIds = "";
                    if ( to != null )
                    {
                        toAddress = InternetAddress.parse ( to );
                        for ( int i = 0; i < toAddress.length; i++ )
                        {
                            InternetAddress temp = toAddress[i];
                            String address = temp.getAddress ();
                            //modified by varma to remove ; at the end of mail list
                            /*if ( address.indexOf ( companyEmailId ) == -1 )
                            {
                                emailIds = emailIds + temp.getAddress () + "; ";
                            } */
                             if ( address.indexOf ( companyEmailId ) == -1 )
                            {
                                if(emailIds == "" )
                                {
                                emailIds = emailIds + temp.getAddress () ;
                                }
                                else
                                {
                                 emailIds = emailIds +", "+ temp.getAddress () ;
                                }
                            }
                        }
                    }
                    if ( cc != null )
                    {
                        ccAddress = InternetAddress.parse ( cc );
                        for ( int i = 0; i < ccAddress.length; i++ )
                        {
                            InternetAddress temp = ccAddress[i];
                            String address = temp.getAddress ();
                            if ( address.indexOf ( companyEmailId ) == -1 )
                            {
                                //emailIds = emailIds + temp.getAddress () + ";  ";
                                 if(emailIds == "" )
                                {
                                emailIds = emailIds + temp.getAddress () ;
                                }
                                else
                                {
                                 emailIds = emailIds +", "+ temp.getAddress () ;
                                }
                            }
                        }
                    }
                    if ( bcc != null )
                    {
                        bccAddress = InternetAddress.parse ( bcc );
                        for ( int i = 0; i < bccAddress.length; i++ )
                        {
                            InternetAddress temp = bccAddress[i];
                            String address = temp.getAddress ();
                            if ( address.indexOf ( companyEmailId ) == -1 )
                            {
                                //emailIds = emailIds + temp.getAddress () + ";  ";
                                 if(emailIds == "" )
                                {
                                emailIds = emailIds + temp.getAddress () ;
                                }
                                else
                                {
                                 emailIds = emailIds +", "+ temp.getAddress () ;
                                }
                            }
                        }
                    }

                    if ( emailIds.trim ().length () > 0 )
                    {
                        errors.put ( "The following e-mails are going out of the company. Please confirm to send them.", null );
                       // info.put ( "Emails: ", emailIds );
                          info.put ( "Emails ", emailIds );
                        session.setAttribute ( "isConfirm", "True" );
                        return mapping.findForward ( "success" );
                    }
                }

                mailAttachments = new String[]{proFormaFile};
                Mailer.send ( from, to, cc, bcc, subject, message, mailAttachments, Mailer.CONTENT_TYPE_HTML, false );
                //info.put ( "Email has been sent, successfully", null );
                  info.put ( "Email has been sent successfully", null );
                session.removeAttribute ( "ShowAgain" );
                session.removeAttribute ( "isConfirm" );
            }
            catch ( Exception se )
            {
                success = false;

                String errMessage = "Internal Server Error";

                errors.put ( errMessage, "Could not send Email" );
                se.printStackTrace ();
            }

            return ( mapping.findForward ( "sendProFormaMailView" ) );
        }
        else if ( "showContactPersonDetails".equalsIgnoreCase ( action ) )
        {
            try
            {
                String value = ( String ) session.getAttribute ( "ShowAgain" );
                if ( "True".equals ( value ) )
                {

                    contactPersons = ( ArrayList ) session.getAttribute ( "contactPersons" );
                }
                else
                {
                // To get Customer related ,Sales Order Billing  ,Sales Order Shipping - Contact Person Emalids
                    contactPersons = CustomerDAO.getAllContactPersonsWithEmails ( null, salesOrder );
                    /*int contactPersonsSize = contactPersons.size ();
                    for ( int i = 0; i < contactPersonsSize; i++ )
                    {
                        ContactPerson cperson = ( ContactPerson ) contactPersons.get ( i );
                    } */
                    int contactPersonsSize = 0;
                    if( contactPersons != null )
                    {
                        contactPersonsSize = contactPersons.size();
                    }
                    int userEmailsSize = 0;
                    ArrayList  userEmailsList = new ArrayList();
                    try
                    {
                        userEmailsList = UserDAO.loadEmailsByType(Constants.USER_NOTIFICATION_EMAIL_TYPE_FOR_PROFORMA_INVOICE);
                    }
                    catch( ScalarException se )
                    {
                        se.getRootCause().printStackTrace();
                        System.out.println( "Exception while retrieving email list");
                    }
                    if( userEmailsList != null )
                    {
                       userEmailsSize = userEmailsList.size();
                    }
                    types = new String[ contactPersonsSize + userEmailsSize + 2 ];

                    int i = 0;
                    //added by varma 26 jul 2004
                    for ( i = 0; i < contactPersons.size (); i++ )
                    {
                        ContactPerson contactPerson = ( ContactPerson ) contactPersons.get ( i );

                        if ( contactPerson.getProformaInvoice() )
                        {
                            contactPerson.setIsChecked ( true );
                        }
                        types[i] = "Contact Person";
                   }
                    //Aded by varma 20 dec 2004
                   int billingAddressId = SalesOrderDAO.getDefaultBillingAddressId( salesOrder.getCustomerId() );
                   String customerEmail    = CustomerDAO.getAddress( billingAddressId ).getEmail();

                   if ( customerEmail != null && !"".equals(customerEmail.trim()) )
                   {
                       ContactPerson customer = new ContactPerson();
                       customer.setContactPerson(salesOrder.getCustomerName());
                       customer.setEmail( customerEmail );
                       contactPersons.add(customer);
                       types[i++] = "Customer";
                   }
                   if ( userEmailsList != null && userEmailsSize > 0 )
                    {
                       for( int j = 0; j < userEmailsSize; j++ )
                       {
                           ContactPerson customer = new ContactPerson();
                           StringTokenizer st = new StringTokenizer ( ( String )userEmailsList.get(j), "/" );
                           String userName = st.nextToken ();
                           String userEmail = st.nextToken ();
                           customer.setContactPerson( userName );
                           customer.setEmail( userEmail );
                           customer.setIsChecked( true );
                           contactPersons.add(customer);
                           types[i++] = "User";
                       }
                    }
                   session.setAttribute ("types",types);
                }
            }
            catch ( ScalarException e )
            {
                e.printStackTrace ();
            }
            session.setAttribute ( "ShowAgain", "False" );
            request.setAttribute ( "contactPersons", contactPersons );
            return ( mapping.findForward ( "showContactPersons" ) );
        }
        else if ( "displayMailIds".equalsIgnoreCase ( action ) )
        {
            try
            {
            // To get Customer related ,Sales Order Billing  ,Sales Order Shipping - Contact Person Emalids
                contactPersons = CustomerDAO.getAllContactPersonsWithEmails ( null, salesOrder );
                int billingAddressId = SalesOrderDAO.getDefaultBillingAddressId( salesOrder.getCustomerId() );
                String customerEmail    = CustomerDAO.getAddress( billingAddressId ).getEmail();
                int userEmailsSize = 0;
                ArrayList  userEmailsList = new ArrayList();
                try
                {
                    userEmailsList = UserDAO.loadEmailsByType(Constants.USER_NOTIFICATION_EMAIL_TYPE_FOR_PROFORMA_INVOICE);
                }
                catch( ScalarException se )
                {
                    se.getRootCause().printStackTrace();
                    System.out.println( "Exception while retrieving email list");
                }
                if( userEmailsList != null )
                {
                   userEmailsSize = userEmailsList.size();
                }
                if ( customerEmail != null && !"".equals(customerEmail.trim()) )
                {
                    ContactPerson customer = new ContactPerson();
                    customer.setContactPerson(salesOrder.getCustomerName());
                    customer.setEmail( customerEmail );
                    contactPersons.add(customer);
                }
                if ( userEmailsList != null && userEmailsSize > 0 )
                {
                   for( int j = 0; j < userEmailsSize; j++ )
                   {
                       ContactPerson customer = new ContactPerson();
                       StringTokenizer st = new StringTokenizer ( ( String )userEmailsList.get(j), "/" );
                       String userName = st.nextToken ();
                       String userEmail = st.nextToken ();
                       customer.setContactPerson( userName );
                       customer.setEmail( userEmail );
                       contactPersons.add(customer);
                   }
                }
                for ( int i = 0; i < contactPersons.size (); i++ )
                {
                    ContactPerson contactPerson = ( ContactPerson ) contactPersons.get ( i );

                    if ( request.getParameter ( "selectedValue" + i ) != null )
                    {
                        contactPerson.setIsChecked ( true );
                    }
                }
                session.setAttribute ( "contactPersons", contactPersons );
                session.setAttribute ( "ShowAgain", "True" );
            }
            catch ( Exception se )
            {
                System.out.println ( "Exception while loading Pro Forma Invoice emails.. " );
            }
            return ( mapping.findForward ( "success" ) );
        }

        try
        {
            subject = sendProFormaMailForm.getSubject ();
            ContactPerson cperson = null;//added by varma(28jun2004)
            if ( subject == null )
            {
               //To add customer Name to subject
                subject = customerName + " Pro Forma Invoice for  " + customerPO; //modified  by sarada to show customer PO in subject
            }
            sendProFormaMailForm.setSubject ( subject );
             //added by varma(28jun2004) to set the contact person mail ids  as To ids
            toUsers = sendProFormaMailForm.getToUsers();
            if(toUsers == null)
            {
                contactPersons = CustomerDAO.getAllContactPersonsWithEmails ( null, salesOrder );
                int contactPersonsSize = contactPersons.size ();
                int userEmailsSize = 0;
                int i = 0;
                int k = 0;

                ArrayList  userEmailsList = new ArrayList();
                try
                {
                    userEmailsList = UserDAO.loadEmailsByType(Constants.USER_NOTIFICATION_EMAIL_TYPE_FOR_PROFORMA_INVOICE);
                }
                catch( ScalarException se )
                {
                    se.getRootCause().printStackTrace();
                    System.out.println( "Exception while retrieving email list");
                }
                if( userEmailsList != null )
                {
                   userEmailsSize = userEmailsList.size();
                }

                String [] mailTo =new String[contactPersonsSize + userEmailsSize];
                for ( i = 0; i < contactPersonsSize; i++ )
                {
                   cperson = ( ContactPerson ) contactPersons.get ( i );
                   if( cperson.getProformaInvoice() )
                   {
                      mailTo[i] = cperson.getEmail();
                   }
               }
               for ( k = 0; k < userEmailsSize; k++) {
                    StringTokenizer st = new StringTokenizer ( ( String )userEmailsList.get(k), "/" );
                    String userName = st.nextToken ();
                    String userEmail = st.nextToken ();
                    mailTo[ i + k ] = userEmail;
                }

                  sendProFormaMailForm.setToUsers(mailTo);
            }
        }

        catch ( Exception se )
        {
            System.out.println ( "Exception while loading Pro Forma Invoice emails.. " );

        }
        session.removeAttribute ( "ShowAgain" );
        session.removeAttribute ( "isConfirm" );
         //commented by varma(28jun2004)
        //String[] finalemail = {""};
       // sendProFormaMailForm.setToUsers ( finalemail );

        sendProFormaMailForm.setCustomerId ( salesOrder.getCustomerId () );
        request.setAttribute ( "sendProFormaMailForm", sendProFormaMailForm );
        return ( mapping.findForward ( "success" ) );
    }
}